package com.tsunami.activity;

import java.util.Calendar;

import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.tsunami.R;
import com.tsunami.activity.TodoListActivity.TodoListFragment.TaskDetailFragment;
import com.tsunami.adapter.TaskAdapter;
import com.tsunami.provider.TodoList;

public class TodoListActivity extends Activity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_task);	
	}
	
	public static class TodoListFragment extends ListFragment 
							implements LoaderManager.LoaderCallbacks<Cursor>{

        SimpleCursorAdapter mAdapter;
        int curCheckPosition = 0;
        int shownCheckPosition = -1;
        Menu optionMenu;
        TodoTaskFragment task = null;

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {

			super.onActivityCreated(savedInstanceState);
			
			getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			setHasOptionsMenu(true);
			registerForContextMenu(getListView());
			
			mAdapter = new SimpleCursorAdapter(getActivity(),
					android.R.layout.simple_list_item_activated_2, null,
					new String[] { TodoList.List.COLUMN_NAME_TITLE },
					new int[] { android.R.id.text1 }, 0);
			setListAdapter(mAdapter);

			getLoaderManager().initLoader(0, null, this);

			if (savedInstanceState != null) {
				// Restore last state for checked position.
				Toast.makeText(getActivity(), "restore", Toast.LENGTH_LONG).show();
				curCheckPosition = savedInstanceState.getInt("curChoice", 0);
				shownCheckPosition = savedInstanceState.getInt("shownChoice",
						-1);
				showTasks(curCheckPosition);
			}
		}
		
		

      
		@Override
		public boolean onContextItemSelected(MenuItem item) {
			AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
			
			switch (item.getItemId()) {
			case R.id.editTitle:
				TextView v = ((TextView)info.targetView.findViewById(android.R.id.text1));
				NewListDialogFragment dialog = NewListDialogFragment.newInstance(info.id, v.getText());
				dialog.show(getFragmentManager(), "dialog");
				return true;
			case R.id.delete:	
				ContentResolver contentResolver = getActivity().getContentResolver();
				contentResolver.delete(TodoList.Task.CONTENT_URI, TodoList.Task.COLUMN_NAME_LIST_ID+"=?", new String[]{String.valueOf(info.id)});
				contentResolver.delete(Uri.withAppendedPath(TodoList.List.CONTENT_ID_URI_BASE, String.valueOf(info.id)), null, null);
				if (shownCheckPosition == info.position) {
					curCheckPosition = 0;
				}
				return true;
			default:
				return super.onContextItemSelected(item);
			}			
		}



		
		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			super.onCreateContextMenu(menu, v, menuInfo);
			MenuInflater inflater = getActivity().getMenuInflater();
			inflater.inflate(R.menu.list_item_menu, menu);
		}


		@Override 
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
			//Toast.makeText(getActivity(), "onCreateOptionsMenu", Toast.LENGTH_LONG).show();
			inflater.inflate(R.menu.task_menu, menu);	
			optionMenu = menu;
			
			adjustActionBarItem();   
        }
		
		@Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putInt("curChoice", curCheckPosition);
            outState.putInt("shownChoice", shownCheckPosition);
        }

        @Override
		public boolean onOptionsItemSelected(MenuItem item) {
			switch(item.getItemId()) {
				case R.id.new_list:
					NewListDialogFragment dialog = NewListDialogFragment.newInstance(-1, null);
					dialog.show(getFragmentManager(), "dialog");
					return true;
				case R.id.new_task:
					long id = getListView().getItemIdAtPosition(shownCheckPosition);
					TaskDetailFragment taskDialog = TaskDetailFragment.newInstance(-1, id, task.getTaskCount());
					taskDialog.show(getFragmentManager(), "dialog");
					return true;
				default:
					return super.onOptionsItemSelected(item);
			}
		}
		
		void showTasks(int position) {
			curCheckPosition = position;
			long id = getListView().getItemIdAtPosition(position);	
			
			if (curCheckPosition != shownCheckPosition) {
				getListView().setItemChecked(position, true);
				task = TodoTaskFragment.newInstance(id);
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				ft.replace(R.id.tasks, task);
				ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				//ft.commit();
				ft.commitAllowingStateLoss();
				shownCheckPosition = position;
			}
		}
        
		@Override 
        public void onListItemClick(ListView l, View v, int position, long id) {
			showTasks(position);			
        }
		
		

        static final String[] PROJECTION = new String[] {
            TodoList.List._ID,
            TodoList.List.COLUMN_NAME_TITLE,
            TodoList.List.COLUMN_NAME_CREATED_DATE,
            TodoList.List.COLUMN_NAME_SOURCE,
            TodoList.List.COLUMN_NAME_DISPLAY_ORDER
        };

		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			return new CursorLoader(getActivity(), TodoList.List.CONTENT_URI, PROJECTION, null,
					null, null);
		}

        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        	//Toast.makeText(getActivity(), "onLoadFinished", Toast.LENGTH_LONG).show();
        	mAdapter.swapCursor(data);
        	showTasks(curCheckPosition);
        	adjustActionBarItem();         
        }
        
        void adjustActionBarItem() {
        	int count = getListView().getCount();
			optionMenu.findItem(R.id.new_task).setVisible(count>0? true : false);
        }




		public void onLoaderReset(Loader<Cursor> loader) {
            mAdapter.swapCursor(null);
        }
		
		public static class TaskDetailFragment extends DialogFragment {
			
			private static long taskId = -1;
			private static long listId = -1;
			private static int taskCount = -1;
			
			static TaskDetailFragment newInstance(long _taskId, long _listId, int _taskCount) {
				taskId = _taskId;
				listId = _listId;
				taskCount = _taskCount;
				return new TaskDetailFragment();
			}
			
			@Override
			public void onCreate(Bundle savedInstanceState) {
				super.onCreate(savedInstanceState);
				this.setCancelable(true);
				int style = DialogFragment.STYLE_NORMAL;
				int theme = android.R.style.Theme_Holo_DialogWhenLarge;
				setStyle(style, theme);
			}

			
			@Override
			public View onCreateView(LayoutInflater inflater,
					ViewGroup container, Bundle savedInstanceState) {
				
				getDialog().setTitle(R.string.task_detail);
				View v = inflater.inflate(R.layout.task_detail,container,false);
				if (taskId != -1) {
					Button delete = (Button) v.findViewById(R.id.delete);
					delete.setVisibility(View.VISIBLE);
					delete.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							getActivity().getContentResolver().delete(Uri.withAppendedPath(TodoList.Task.CONTENT_ID_URI_BASE, String.valueOf(taskId)), null, null);
							getDialog().dismiss();						
						}
					});
					
					
					Cursor c = getActivity().getContentResolver().query(Uri.withAppendedPath(TodoList.Task.CONTENT_ID_URI_BASE, String.valueOf(taskId)), TodoTaskFragment.PROJECTION, null, null, null);
					if (c.moveToFirst()) {
						EditText desc = (EditText) v.findViewById(R.id.task_desc);
						desc.setText(c.getString(c.getColumnIndex(TodoList.Task.COLUMN_NAME_DESCRIPTION)));
						Long time = c.getLong(c.getColumnIndex(TodoList.Task.COLUMN_NAME_DUE_DATE));
						//Toast.makeText(getActivity(), String.valueOf(time), Toast.LENGTH_LONG).show();
						if (time != 0) {
							Calendar calendar = Calendar.getInstance();
							calendar.setTimeInMillis(time);
							CheckBox box = (CheckBox) v.findViewById(R.id.checkBox_date);
							box.setChecked(true);
							DatePicker datePicker = (DatePicker) v.findViewById(R.id.datePicker);
							datePicker.setVisibility(View.VISIBLE);
							datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONDAY), calendar.get(Calendar.DAY_OF_MONTH), null);
							
							box = (CheckBox) v.findViewById(R.id.checkBox_time);
							box.setChecked(true);
							TimePicker timePicker = (TimePicker) v.findViewById(R.id.timePicker);
							timePicker.setVisibility(View.VISIBLE);
							timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
							timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));
						}
					}				
					
				}
				
				Button save = (Button) v.findViewById(R.id.save);
				save.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {	
						
						EditText descText = (EditText) getDialog().findViewById(R.id.task_desc);
						String desc = descText.getText().toString();
						
						ContentValues values = new ContentValues();
						values.put(TodoList.Task.COLUMN_NAME_DESCRIPTION, desc);
						
						Calendar calendar = null;
						CheckBox dBox = (CheckBox) getView().findViewById(R.id.checkBox_date);
						CheckBox tBox = (CheckBox) getView().findViewById(R.id.checkBox_time);
						if (dBox.isChecked() || tBox.isChecked()) {
							calendar = Calendar.getInstance();
							if (dBox.isChecked()) {
								DatePicker datePicker = (DatePicker) getView().findViewById(R.id.datePicker);
								calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
							}
							if (tBox.isChecked()) {
								TimePicker timePicker = (TimePicker) getView().findViewById(R.id.timePicker);
								calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
								calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
							}
						}
						values.put(TodoList.Task.COLUMN_NAME_DUE_DATE, calendar==null? null : calendar.getTimeInMillis());
						
						if (taskId == -1) {
							if (false == TextUtils.isEmpty(desc)) {
								values.put(TodoList.Task.COLUMN_NAME_LIST_ID, listId);
								
								values.put(TodoList.Task.COLUMN_NAME_DISPLAY_ORDER, taskCount+1);
								getActivity().getContentResolver().insert(TodoList.Task.CONTENT_URI, values);
							}
						} else {
							getActivity().getContentResolver().update(Uri.withAppendedPath(TodoList.Task.CONTENT_ID_URI_BASE, String.valueOf(taskId)), values, null, null);
						}						
						getDialog().dismiss();						
					}
				});
				
				
				Button cancel = (Button) v.findViewById(R.id.cancel);
				cancel.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {										
						getDialog().dismiss();						
					}
				});
				
				//DatePicker datePicker = (DatePicker) v.findViewById(R.id.datePicker);
				//datePicker.setMinDate(System.currentTimeMillis());
				//datePicker.setVisibility(View.INVISIBLE);
				
				CheckBox dBox = (CheckBox) v.findViewById(R.id.checkBox_date);
				dBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						DatePicker datePicker = (DatePicker) getView().findViewById(R.id.datePicker);
						//CheckBox cBox = (CheckBox) getView().findViewById(R.id.checkBox_time);
						if (isChecked) {
							datePicker.setVisibility(View.VISIBLE);
							//cBox.setVisibility(View.VISIBLE);
						} else {
							datePicker.setVisibility(View.INVISIBLE);
							//cBox.setVisibility(View.INVISIBLE);
						}
					}
				});
				
				//TimePicker timePicker = (TimePicker) v.findViewById(R.id.timePicker);
				//timePicker.setIs24HourView(true);
				//Toast.makeText(getActivity(), String.valueOf(timePicker.getCurrentHour()), Toast.LENGTH_LONG).show();
				//timePicker.setVisibility(View.INVISIBLE);
				
				CheckBox tBox = (CheckBox) v.findViewById(R.id.checkBox_time);
				tBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						TimePicker timePicker = (TimePicker) getView().findViewById(R.id.timePicker);
						if (isChecked) 
							timePicker.setVisibility(View.VISIBLE);
						else 
							timePicker.setVisibility(View.INVISIBLE);
					}
				});
				
				return v;
			}
			
			
		}
        
		public static class NewListDialogFragment extends DialogFragment {
			
			private static CharSequence title = null;
			private static long listId = -1;

			
			
			static NewListDialogFragment newInstance(long _listId, CharSequence _title) {
				listId = _listId;
				title = _title;
				return new NewListDialogFragment();
			}

			@Override
			public void onCreate(Bundle savedInstanceState) {
				super.onCreate(savedInstanceState);
				this.setCancelable(true);
				int style = DialogFragment.STYLE_NORMAL;
				int theme = android.R.style.Theme_Holo_DialogWhenLarge;
				setStyle(style, theme);
			}

			
			@Override
			public View onCreateView(LayoutInflater inflater,
					ViewGroup container, Bundle savedInstanceState) {
				getDialog().setTitle(listId==-1 ? R.string.new_list_title : R.string.edit_title);
				View v = inflater.inflate(R.layout.new_list_dialog,container,false);
				
				if (title != null) {
					EditText editText = (EditText) v.findViewById(R.id.title);
					editText.setText(title);
				}
				
				Button done = (Button) v.findViewById(R.id.done);
				done.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {						
						EditText editText = (EditText) getDialog().findViewById(R.id.title);
						String title = editText.getText().toString();
						if (false == TextUtils.isEmpty(title)) {
							ContentValues values = new ContentValues();
							values.put(TodoList.List.COLUMN_NAME_TITLE, title);
							if (listId == -1) 							
								getActivity().getContentResolver().insert(TodoList.List.CONTENT_URI, values);
							else 
								getActivity().getContentResolver().update(Uri.withAppendedPath(TodoList.List.CONTENT_ID_URI_BASE, String.valueOf(listId)), values, null, null);
						}
						getDialog().dismiss();						
					}
				});
		        return v;
			}
			
		}
	
	}

	
	
	public static class TodoTaskFragment extends ListFragment 
								implements LoaderManager.LoaderCallbacks<Cursor>{
		
		SimpleCursorAdapter mAdapter;
		
		static long listId;

		public static TodoTaskFragment newInstance(long _listId) {
			listId = _listId;
			TodoTaskFragment task = new TodoTaskFragment();
			return task;
		}
		
		public int getTaskCount() {
			return mAdapter.getCount();
		}
		
		@Override 
        public void onListItemClick(ListView l, View v, int position, long id) {
			TaskDetailFragment taskDialog = TaskDetailFragment.newInstance(id, listId, getTaskCount());
			taskDialog.show(getFragmentManager(), "dialog");
        }
		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);

			setHasOptionsMenu(true);

			mAdapter = new TaskAdapter(getActivity(), R.layout.task_item, null,
					new String[] { TodoList.Task.COLUMN_NAME_DESCRIPTION },
					new int[] { R.id.desc });
			setListAdapter(mAdapter);

			getLoaderManager().initLoader(0, null, this);

		}
		
		static final String[] PROJECTION = new String[] {
            TodoList.Task._ID,
            TodoList.Task.COLUMN_NAME_COMPLETED_DATE,
            TodoList.Task.COLUMN_NAME_CREATED_DATE,
            TodoList.Task.COLUMN_NAME_DESCRIPTION,
            TodoList.Task.COLUMN_NAME_DISPLAY_ORDER,
            TodoList.Task.COLUMN_NAME_DUE_DATE,
            TodoList.Task.COLUMN_NAME_LIST_ID,
            TodoList.Task.COLUMN_NAME_NOTES
        };
		
		public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		
			Uri baseUri = TodoList.Task.CONTENT_URI;
			return new CursorLoader(getActivity(), baseUri, PROJECTION, TodoList.Task.COLUMN_NAME_LIST_ID+"=?",
					new String[]{String.valueOf(listId)}, null);
		}

		public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
			 mAdapter.swapCursor(data);
			
		}

		public void onLoaderReset(Loader<Cursor> loader) {
			 mAdapter.swapCursor(null);
			
		}
		
		
		
	}
}
